package inAction;

import java.io.File;
import java.util.Date;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

//page 51
public class Searcher {
	public static void main(String[] args) throws Exception {
		search(new File("index\\indexed"), "aaaa");
//		searchLine(new File("index\\indexed"), "bbbb");
//		search(new File("index\\indexed"), "D:\\ws\\lucene-practise\\index\\toBeIndexed\\abc.txt");
	}

	public static void search(File indexDir, String q) throws Exception {
		IndexReader reader = IndexReader.open(FSDirectory.open(indexDir));
		Directory fsDir = FSDirectory.open(indexDir);
		IndexSearcher is = new IndexSearcher(fsDir);
		QueryParser parser = new QueryParser(Version.LUCENE_34,"contents", new StandardAnalyzer(Version.LUCENE_34));
//		QueryParser parser1 = new QueryParser("filename", new StandardAnalyzer());
		Query query = parser.parse(q);
//		Query query1 = parser.parse(q);
		TopDocs hits = is.search(query, null, 10);
		for (int i = 0; i < hits.totalHits; i++) {
			int docId = hits.scoreDocs[i].doc;
			Document d = is.doc(docId);
			System.out.println(d.get("filename"));
		}
	}
	
	public static void searchLine(File indexDir, String q) throws Exception {
		Directory fsDir = FSDirectory.open(indexDir);
		IndexSearcher is = new IndexSearcher(fsDir);
		QueryParser parser = new QueryParser(Version.LUCENE_34,"id", new StandardAnalyzer(Version.LUCENE_34));
//		QueryParser parser1 = new QueryParser("filename", new StandardAnalyzer());
		Query query = parser.parse(q);
		Query query1 = new TermQuery(new Term("id","3"));
		
		TopDocs hits = is.search(query1, null, 10);
		for (int i = 0; i < hits.totalHits; i++) {
			int docId = hits.scoreDocs[i].doc;
			Document d = is.doc(docId);
			System.out.println(d.get("value"));
		}
	}
}
